from fastapi import APIRouter, UploadFile, File, HTTPException, Form
from fastapi.responses import StreamingResponse, Response, JSONResponse
from app.models.response import ApiResponse
from app.services.audio_service import AudioService
from app.utils.file_utils import validate_file_type
from app.config import settings
import io
from typing import List
import logging

logger = logging.getLogger(__name__)
router = APIRouter()

@router.post(
    "/convert",
    response_class=Response,
    summary="转换音频格式",
    description="将音频转换为其他格式"
)
async def convert_audio(
    file: UploadFile = File(...),
    format: str = Form(..., description="目标格式，如：mp3, wav, ogg")
):
    try:
        if not validate_file_type(file.filename, settings.ALLOWED_EXTENSIONS["audio"]):
            return JSONResponse(
                status_code=400,
                content={"message": "不支持的文件格式"}
            )
            
        content = await file.read()
        result = await AudioService.convert_format(content, format)
        
        output_filename = f"{file.filename.rsplit('.', 1)[0]}.{format}"
        
        return Response(
            content=result,
            media_type=f"audio/{format}",
            headers={
                "Content-Disposition": f'attachment; filename="{output_filename}"',
                "Content-Length": str(len(result))
            }
        )
    except ValueError as e:
        return JSONResponse(
            status_code=400,
            content={"message": str(e)}
        )
    except Exception as e:
        logger.error(f"转换失败: {str(e)}")
        return JSONResponse(
            status_code=500,
            content={"message": "转换失败"}
        )

@router.post(
    "/compress",
    summary="音频压缩",
    description="压缩音频文件，可调整比特率"
)
async def compress_audio(
    file: UploadFile = File(...),
    bitrate: int = 128
):
    """压缩音频"""
    try:
        if not validate_file_type(file.filename, ['.mp3', '.wav', '.ogg', '.aac', '.flac']):
            raise HTTPException(400, "不支持的文件格式")

        content = await file.read()
        result = await AudioService.compress_audio(content, bitrate)
        
        return StreamingResponse(
            io.BytesIO(result),
            media_type="audio/mp3",
            headers={"Content-Disposition": "attachment; filename=compressed.mp3"}
        )
    except Exception as e:
        raise HTTPException(500, "音频压缩失败")

@router.post(
    "/trim",
    response_class=Response,
    summary="剪辑音频",
    description="按时间范围剪辑音频文件"
)
async def trim_audio(
    file: UploadFile = File(...),
    start_time: float = Form(..., description="开始时间（秒）"),
    end_time: float = Form(..., description="结束时间（秒）")
):
    try:
        if not validate_file_type(file.filename, settings.ALLOWED_EXTENSIONS["audio"]):
            return JSONResponse(
                status_code=400,
                content={"message": "不支持的文件格式"}
            )
            
        content = await file.read()
        result = await AudioService.trim_audio(content, start_time, end_time)
        
        return Response(
            content=result,
            media_type="audio/mpeg"
        )
    except Exception as e:
        logger.error(f"剪辑失败: {str(e)}")
        return JSONResponse(
            status_code=400,
            content={"message": str(e)}
        )

@router.post(
    "/merge",
    response_class=Response,
    summary="合并音频",
    description="将多个音频文件合并为一个"
)
async def merge_audio(
    files: List[UploadFile] = File(..., description="音频文件列表")
):
    try:
        contents = []
        for file in files:
            if not validate_file_type(file.filename, settings.ALLOWED_EXTENSIONS["audio"]):
                return JSONResponse(
                    status_code=400,
                    content={"message": "不支持的文件格式"}
                )
            content = await file.read()
            contents.append(content)
            
        result = await AudioService.merge_audio(contents)
        
        return Response(
            content=result,
            media_type="audio/mpeg"
        )
    except Exception as e:
        logger.error(f"合并失败: {str(e)}")
        return JSONResponse(
            status_code=400,
            content={"message": str(e)}
        ) 